package com.lxp.base.adapter;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by lxp on 2017/8/21.
 * DataBinding 适配器
 */

public abstract class DataBindingAdapter<T, K extends ViewDataBinding> extends RecyclerView.Adapter<DataBindingAdapter.ViewHolder> {

    private int mLayoutResId;
    private List<T> mData;
    private Context mContext;

    public DataBindingAdapter(int layoutResId, @Nullable List<T> data) {
        this.mLayoutResId = layoutResId;
        this.mData = data;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mContext=parent.getContext();
        View view = View.inflate(mContext, mLayoutResId, null);
        return new ViewHolder<K>(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        onBindView((K) holder.getBinding(), mData.get(position));
        holder.getBinding().executePendingBindings();
    }

    @Override
    public int getItemCount() {
        if (null != mData) {
            return mData.size();
        } else {
            return 0;
        }

    }

    class ViewHolder<K extends ViewDataBinding> extends RecyclerView.ViewHolder {
        private K binding;

        public ViewHolder(View itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);
        }

        public K getBinding() {
            return binding;
        }
    }

    /**
     * 刷新数据
     *
     * @param mData
     */
    public void setNewData(List<T> mData) {
        this.mData.clear();
        this.mData.addAll(mData);
        notifyDataSetChanged();
    }

    /**
     * 绑定数据
     *
     * @param binding
     * @param item
     */
    public abstract void onBindView(K binding, T item);
}
